package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.SysAttachment;
import com.ruoyi.system.service.ISysAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * 附件管理 服务层实现
 *
 * @author ZouYangMing
 */
@Service
public class ISysAttachmentServiceImpl implements ISysAttachmentService {

    @Autowired
    private RedisCache redisCache;

    private final String ATTACHMENT_KEY = CacheConstants.FILE_LIST + "list";

    /**
     * 获取附件列表
     *
     * @return 附件列表
     */
    @Override
    public List<SysAttachment> getFileList(SysAttachment sysAttachment) {
        // 判断Redis中是否存在附件列表
        List<SysAttachment> cacheFileList = redisCache.getCacheList(ATTACHMENT_KEY);
        if (cacheFileList.size() > 0) {
            // 搜索操作
            if (StringUtils.isNotEmpty(sysAttachment.getFileName())) {
                cacheFileList.removeIf(sysFile -> !sysFile.getFileName().contains(sysAttachment.getFileName()));
            }
            return cacheFileList;
        }
        String profile = RuoYiConfig.getProfile();
        List<File> filesInFolderList = FileUtils.getFilesInFolderList(profile);
        List<SysAttachment> sysFileList = new ArrayList<>();
        filesInFolderList.forEach(file -> {
            SysAttachment sysFile = new SysAttachment();
            sysFile.setFileName(file.getName());
            String absolutePath = file.getAbsolutePath().replaceAll("\\\\", "/"); // 获取文件绝对路径 将绝对路径中的 \\ 替换为 /
            sysFile.setFilePath(absolutePath);
            sysFile.setFileSize(file.length());
            // 获取文件类型
            String mimeType;
            try {
                FileInputStream inputFile = new FileInputStream(file);
                mimeType = URLConnection.guessContentTypeFromStream(new BufferedInputStream(inputFile));
                inputFile.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            sysFile.setFileType(mimeType);
            // 获取文件访问地址
            String currentDir = Constants.RESOURCE_PREFIX + "/" + StringUtils.substring(absolutePath, RuoYiConfig.getProfile().length() + 1);
            sysFile.setFileUrl(currentDir);
            sysFileList.add(sysFile);
        });
        if (sysFileList.size() > 0) {
            // 将附件列表存入Redis
            redisCache.setCacheList(ATTACHMENT_KEY, sysFileList);
        }
        // 搜索操作
        if (StringUtils.isNotEmpty(sysAttachment.getFileName())) {
            sysFileList.removeIf(sysFile -> !sysFile.getFileName().contains(sysAttachment.getFileName()));
        }
        return sysFileList;
    }

    /**
     * 查询附件列表
     *
     * @param sysAttachment 附件信息
     * @return 附件列表
     */
    @Override
    public List<SysAttachment> queryFileList(SysAttachment sysAttachment) {
        List<SysAttachment> files = this.getFileList(sysAttachment);
        // 搜索操作
        if (StringUtils.isNotEmpty(sysAttachment.getFileName())) {
            files.removeIf(sysFile -> !sysFile.getFileName().contains(sysAttachment.getFileName()));
        }
        return files;
    }

    /**
     * 批量删除附件
     *
     * @param fileList 附件列表
     */
    @Override
    public void deleteFileList(String[] fileList) {
        for (String filePath : fileList) {
            try {
                Files.delete(new File(filePath).toPath());
                redisCache.deleteObject(ATTACHMENT_KEY);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 删除附件
     *
     * @param filePath 文件路径
     */
    @Override
    public void deleteFile(String filePath) {
        try {
            Files.delete(new File(filePath).toPath());
            redisCache.deleteObject(ATTACHMENT_KEY);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
